function [ gf1, opp1 ] = uniteFragments( gf, opp, w )
% Unite fragments with close orientation
%
% Syntax
%   [ gf1, opp1 ] = uniteFragments( gf, opp, w );
%
% Output
%   gf1     - new index of grains in fragments
%   oop1    - new parent orientation of fragments
%
% Input
%   gf      - index of grains in fragments
%   opp     - parent orientation of fragments
%   w       - tolerance angle
%
% History
% 12.04.13  Original implementation

opp1 = opp;
gf1 = gf;
n = length(opp1);
i = 1;

h = waitbar(0,'Unite fragments...');

% For all fragments
while i < n
%     ind = i;
    mis = angle(opp1,opp1(i));
    mm = (mis < w)';
    
    % Coordinates of grain center
    c = centroid(grains);
    
    if (sum(mm) > 1)
        if (isdebug)
            plotpdf(opp1(mm),Miller(1,0,0),'antipodal', 'MarkerSize', 4);
        end
        opp1(i) = mean(opp1(mm));
        gf1{i} = unique([gf1{mm}]);
        a = ~mm;
        b = (1:n == i);
        opp1 = opp1(a | b);
        gf1 = gf1(a | b);
        n = length(opp1);
    end
        
	i = i+1;
    waitbar(i/n);
end
close(h);

if (isfulldebug)
    plotpdf(opp1,Miller(1,0,0),'antipodal', 'MarkerSize', 4);
end

% colorFragments(grains_fe, gf1);
end
